var httpConf = require("../../../conf/httpModule.js")
var async = require("async")
// var historyDB = require("../../../dao/history.js")
module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
    DBRemote.channelService = this.app.get('channelService')
    if(DBRemote.dbService && DBRemote.dbService.db){
    	DBRemote.db = DBRemote.dbService.db
    }
}

var local = {}
var createAccount = function(result,cb) {
	DBRemote.dbService.setUserId(result.unionid,function(playerId) {
		var uid = playerId
		DBRemote.dbService.setPlayer(uid,"diamond",0)
		DBRemote.dbService.setPlayer(uid,"nickname",result.nickname)
		DBRemote.dbService.setPlayer(uid,"head",result.headimgurl)
		DBRemote.dbService.setPlayer(uid,"uid",uid)
		DBRemote.dbService.setPlayer(uid,"sex",result.sex)
		DBRemote.dbService.setPlayer(uid,"limits",10)
		DBRemote.dbService.setPlayer(uid,"freeze",0)
		DBRemote.dbService.setPlayer(uid,"useDiamond",0)
		DBRemote.dbService.setPlayer(uid,"gold",0)
		DBRemote.dbService.setPlayer(uid,"contorl",0)
		DBRemote.dbService.setPlayer(uid,"clubLimit",0)
		if(result.phone){
			DBRemote.dbService.setPlayer(uid,"phone",result.phone)
		}
		if(result.referrer){
			DBRemote.dbService.setPlayer(uid,"referrer",result.referrer)
		}
		//历史战绩
		// var history = {}
		// history.allGames = 0
		// history.List = {}
		// DBRemote.dbService.setPlayerObject(uid,"history",history)
		//每日刷新数据
		var dateString = local.getDateString()
		var refreshList = {}
		refreshList.time =  dateString 				//最后更新时间
		refreshList.shareCount = 0 					//今日分享奖励
		refreshList.gameCount = 0 					//今日游戏轮数
		refreshList.agencyStatistics = {} 			//代开房统计
		refreshList.agencyStatistics[dateString] = {}
		refreshList.agencyStatistics[dateString].useDiamond = 0
		DBRemote.dbService.setPlayerObject(uid,"refreshList",refreshList)
        var tmpObj = {
        	"switch" : "false"
        }
        var cmd = "nn:acc:"+uid+":"+"clubList"
        //俱乐部成员列表
		DBRemote.dbService.db.hmset(cmd,tmpObj,function(){})
		cb(false)
	})
}
DBRemote.prototype.createAccount = function(result,cb) {
	createAccount(result,function() {
		cb(true)
	})
}
//修改昵称
DBRemote.prototype.changeNickname = function(uid,nickname,cb) {
	DBRemote.dbService.setPlayer(uid,"nickname",nickname,cb)
}
//修改头像
DBRemote.prototype.changeHeadType = function(uid,head,cb) {
	DBRemote.dbService.setPlayer(uid,"head",head,cb)
}
//手机登录检查
DBRemote.prototype.checkLoginPhone = function(phone,password,cb) {
	DBRemote.dbService.db.hget("game:phoneAccount",phone,function(err,data) {
		if(err || !data){
			console.log(err)
			console.log(data)
			cb(false)
		}else{
			console.log("password",password,data)
			if(password == data){
				DBRemote.dbService.getUidByUnionid(phone,function(flag,data) {
					if(flag){
						cb(true)
					}else{
						cb(false)
					}
				})
			}else{
				cb(false)
			}
		}
	})
}
//每次登陆更新微信信息
var updateAccount = function(result) {
	var uid = result.playerId
	DBRemote.dbService.setPlayer(uid,"nickname",result.nickname)
	DBRemote.dbService.setPlayer(uid,"head",result.headimgurl)
	DBRemote.dbService.setPlayer(uid,"sex",result.sex)
}
//检查账号是否存在
DBRemote.prototype.check = function(result,cb) {
	//console.log("=================")
	//console.log("result.unionid : "+result.unionid)
	DBRemote.dbService.getPlayerString(result.unionid,"uidMap",function(data) {
		//console.log("data : "+data)
		if(!data){
			createAccount(result,cb)
			//console.log("create ok!!")
		}else{
			result.playerId = parseInt(data)
			updateAccount(result)
			if(cb){
				cb(true)
			}
		}
	})
}
DBRemote.prototype.getPlayerNickName = function(uid,cb) {
	DBRemote.dbService.getPlayerString(uid,"nickname",function(data){
		cb(data)
	})
}
//获取一个空闲ID
DBRemote.prototype.getPlayerId = function(cb) {
	DBRemote.dbService.db.get("nn:acc:lastid",function(err,data) {
		cb(data)
	})
} 

DBRemote.prototype.getPlayerInfoByUid = function(uid,cb) {
	DBRemote.dbService.getPlayerInfoByUid(uid,cb)
}

DBRemote.prototype.getPlayerInfo = function(uid,cb) {
	DBRemote.dbService.getPlayerInfo(uid,cb)
}
DBRemote.prototype.getNotify = function(cb) {
	DBRemote.dbService.getNotify(cb)
}
DBRemote.prototype.updateDiamond = function(value,cb) {
	DBRemote.dbService.updateDiamond(value)
	cb()
}
DBRemote.prototype.updateNotify = function(notify,source,cb) {
	DBRemote.dbService.getNotify(function(data) {
		console.log(data)
		if(!data[source]){
			data[source] = {}
			data[source].name = ""
		}
		data[source].content = notify
		DBRemote.dbService.setNotify(data)
		//更新公告完通知所有玩家
		DBRemote.channelService.broadcast("connector","onNotify",{"type":"notify","data":data})
		if(cb){
			cb(true)
		}
	})
}

//设置抽奖列表
DBRemote.prototype.setLotteryTable = function(data,cb) {
	//参数检测
	if(typeof(data) !== "object"){
		cb(false)
		return
	}
	var count = 0
	for(var i in data){
		if(	parseInt(i) < 0 ||	parseInt(i) > 9 ||
			typeof(data[i].itemId) != "number" || data[i].itemId < 0 ||
			typeof(data[i].itemName) != "string" ||
			typeof(data[i].title) != "string" ||
			typeof(data[i].count) != "number" || data[i].count < 0 ||
			typeof(data[i].weight) != "number" || data[i].weight < 0){
			console.log("参数错误")
			console.log(data)
			cb(false)
			return
		}
		count++
		data[i] = JSON.stringify(data[i])
	}
	if(count !== 10){
		cb(false)
		return
	}
	DBRemote.dbService.db.hmset("gameServer:lotteryTable",data,function(err,data) {
		if(err){
			console.log(err)
			cb(false)
		}else{
			cb(true)
		}
	})
}
//获取抽奖列表
DBRemote.prototype.getLotteryTable = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryTable",function(err,data) {
		for(var i in data){
			data[i] = JSON.parse(data[i])
		}
		cb(data)
	})
}
//获取库存表
DBRemote.prototype.getLotteryInventory = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryInventory",function(err,data) {
		for(var i in data){
			data[i] = parseInt(data[i])
		}
		cb(data)
	})
}
//设置库存表
DBRemote.prototype.setLotteryInventoryItem = function(data,cb) {
	//参数检测
	if(!data.itemId || typeof(data.value) !== "number" || data.value < 0){
		cb(false)
		return
	}
	DBRemote.dbService.db.hset("gameServer:lotteryInventory",data.itemId,data.value,function(err,data){
		if(err){
			console.log(err)
			cb(false)
		}else{
			cb(true)
		}
	})
}
//获取奖品列表
DBRemote.prototype.getLotteryAwardList = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryAwardList",function(err,data){
		for(var i in data){
			data[i] = JSON.parse(data[i])
		}
		cb(data)
	})
}
//设置奖品状态
DBRemote.prototype.sendAwardState = function(uid,orderNumber,state,cb) {
	if(typeof(state) !== "number"){
		cb(false)
		return
	}
	DBRemote.dbService.db.hget("gameServer:lotteryAwardList",uid,function(err,data){
		if(!err && data){
			data = JSON.parse(data)
			if(!data[orderNumber]){
				cb(false)
				return
			}
			data[orderNumber].state = state
			DBRemote.dbService.db.hset("gameServer:lotteryAwardList",uid,JSON.stringify(data),function() {
				cb(true)
			})
		}else{
			cb(false)
		}
	})
}

//获取单个玩家奖品背包
DBRemote.prototype.getLotteryAwardByUid = function(uid,cb) {
	DBRemote.dbService.db.hget("gameServer:lotteryAwardList",uid,function(err,data){
		if(err){
			cb({})
		}else{
			data = JSON.parse(data)
			cb(data)			
		}
	})
}

//获取抽奖记录
DBRemote.prototype.getLotteryHistory = function(cb) {
	DBRemote.dbService.db.lrange("gameServer:lotteryRecordList",-100,-1,function(err,data){
		for(var i in data){
			data[i] = JSON.parse(data[i])
		}
		cb(data)
	})
}
//获取抽奖次数
DBRemote.prototype.getLotteryCount = function(uid,cb) {
	DBRemote.dbService.db.hget("gameServer:lotteryCountList",uid,function(err,data) {
		if(!err && data && data > 0){
			cb(data)
		}else{
			cb(0)
		}
	})
}
//获取抽奖次数列表
DBRemote.prototype.getLotteryCountList = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryCountList",function(err,data) {
		if(!err && data){
			cb(data)
		}else{
			cb({})
		}
	})
}
//获取重要物品记录
DBRemote.prototype.getImportanceAwardList = function(cb) {
	DBRemote.dbService.db.lrange("gameServer:importanceAwardList",-20,-1,function(err,data) {
		if(!err && data){
			for(var i in data){
				data[i] = JSON.parse(data[i])
			}
			cb(data)
		}else{
			cb({})
		}
	})
}
//添加抽奖记录
DBRemote.prototype.addRobotLottery = function(index,cb) {
	if(typeof(index) !== "number" || index < 0 || index > 9){
		cb(false)
		return
	}
	DBRemote.prototype.getLotteryTable(function(data) {
		//抽中奖励
		var info = {
			"index" : index,
			"data" : data[index]
		}
		var id = (new Date()).valueOf() * 100000 + Math.floor(Math.random() * 100000)
		info.uid = Math.floor(Math.random() * 900)
		info.nickname = ""
		//重要物品记录
		info.time =  (new Date()).valueOf()
		if(info.data.importance && info.data.importance === true){
			DBRemote.dbService.db.rpush("gameServer:importanceAwardList",JSON.stringify(info))
			cb(true)
		}else{
			cb(false)
		}
	})
}
//抽奖
DBRemote.prototype.lottery = function(uid,cb) {
	var lotteryTable = {}
	var lotteryInventory = {}
	var nickname = ""
	async.waterfall([
			function(next) {
				//获取抽奖次数
				DBRemote.prototype.getLotteryCount(uid,function(data) {
					if(data > 0){
						next()
					}else{
						console.log("次数不足")
						cb(false)
					}
				})
			},
			function(next) {
				//获取玩家名字
				DBRemote.prototype.getPlayerNickName(uid,function(data) {
					nickname = data
					next()
				})
			},
			function(next) {
				//获取抽奖表
				DBRemote.prototype.getLotteryTable(function(data) {
					lotteryTable = data
					next()
				})
			},
			function(next) {
				//获取抽奖库存
				DBRemote.prototype.getLotteryInventory(function(data) {
					lotteryInventory = data
					next()
				})
			},
			function(next) {
				//抽奖表根据库存调整，无库存的奖励设置权重为0
				var weightAll = 0
				for(var i in lotteryTable){
					if(lotteryTable[i].itemId !== 0 && lotteryTable[i].itemId !== 101 && (!lotteryInventory[lotteryTable[i].itemId] || lotteryInventory[lotteryTable[i].itemId] <= 0)){
						lotteryTable[i].weight = 0
					}
					weightAll += lotteryTable[i].weight
				}
				//获取奖励
				var tmpRand = Math.random() * weightAll
				var weightCur = 0
				for(var i in lotteryTable){
					if(tmpRand >= weightCur && tmpRand < lotteryTable[i].weight + weightCur){
						//扣除次数
						DBRemote.prototype.addLotteryCount(uid,-1)
						//抽中奖励
						var info = {
							"index" : i,
							"data" : lotteryTable[i]
						}
						cb(info)
						//抽奖记录
						var id = (new Date()).valueOf() * 100000 + Math.floor(Math.random() * 100000)
						info.uid = uid
						info.nickname = nickname
						info.id = id
						DBRemote.dbService.db.rpush("gameServer:lotteryRecordList",JSON.stringify(info))
						//重要物品记录
						info.time =  (new Date()).valueOf()
						if(info.data.importance && info.data.importance === true){
							DBRemote.dbService.db.rpush("gameServer:importanceAwardList",JSON.stringify(info))
						}
						switch(lotteryTable[i].itemId){
							case 0 :
								//不处理
							break
							case 101:
								//获得房卡
								DBRemote.prototype.setValue(uid,"diamond",lotteryTable[i].count,function(){})
							break
							default :
								//降低库存
								DBRemote.dbService.db.hincrby("gameServer:lotteryInventory",lotteryTable[i].itemId,-lotteryTable[i].count,function(err) {})
								//获得物品
								DBRemote.dbService.db.hget("gameServer:lotteryAwardList",uid,function(err,data) {
									//查询获奖列表
									if(err || !data){
										data = {}
									}else{
										data = JSON.parse(data)
									}
									var info = {
										"itemId" : lotteryTable[i].itemId,
										"count" : lotteryTable[i].count,
										"itemName" : lotteryTable[i].itemName,
										"title" : lotteryTable[i].title,
										"nickname" : nickname,
										"state" : 0
									}
									data[id] = info
									DBRemote.dbService.db.hset("gameServer:lotteryAwardList",uid,JSON.stringify(data),function(){})
								})
							break
						}
						return
					}else{
						weightCur += lotteryTable[i].weight
					}
				}
				cb(false)
				return
			}
		],function(err,data) {
		console.log(err)
		console.log(data)
	})
}

//抽奖次数增加
DBRemote.prototype.addLotteryCount = function(uid,count,cb) {
	DBRemote.dbService.db.hincrby("gameServer:lotteryCountList",uid,count,function(err) {
		if(!err){
			//通知抽奖次数增加
			var notify = {
				"cmd" : "lotteryCountIncrease",
				"count" : count
			}
			DBRemote.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
			if(cb){
				cb(true)
			}
			if(count > 0){
				//最多保存十次
				DBRemote.dbService.db.hget("gameServer:lotteryCountList",uid,function(err,data) {
					if(!err && data > 10){
						DBRemote.dbService.db.hset("gameServer:lotteryCountList",uid,10,function(err,data){})
					}
				})
			}
		}else{
			if(cb){
				cb(false)
			}
		}
	})
}

DBRemote.prototype.addAgencyRecord = function(uid,diamond,roomType,playerNumber,gameNumber,cb) {
	DBRemote.dbService.getPlayerObject(uid,"refreshList",function(data) {
		if(!data["agencyStatistics"][data.time][roomType]){
			data["agencyStatistics"][data.time][roomType] = {}
		}
		if(!data["agencyStatistics"][data.time][roomType][playerNumber]){
			data["agencyStatistics"][data.time][roomType][playerNumber] = {}
		}
		if(!data["agencyStatistics"][data.time][roomType][playerNumber][gameNumber]){
			data["agencyStatistics"][data.time][roomType][playerNumber][gameNumber] = 0
		}
		data["agencyStatistics"][data.time][roomType][playerNumber][gameNumber]++
		data["agencyStatistics"][data.time].useDiamond += diamond
		DBRemote.dbService.setPlayerObject(uid,"refreshList",data,function(){
			if(cb){
				cb()
			}
		})
	})
}

//游戏局数增加
DBRemote.prototype.addGameCount = function(uid,count,cb) {
	DBRemote.prototype.getPlayerObject(uid,"refreshList",function(data) {
		data.gameCount++
		if(data.gameCount === 20){
			//20轮增加抽奖次数
			console.log("20轮增加抽奖次数")
			DBRemote.prototype.addLotteryCount(uid,count)
		}
		DBRemote.dbService.setPlayerObject(uid,"refreshList",data,function(){
			if(cb){
				cb()
			}
		})
	})
}

DBRemote.prototype.setValue = function(uid,name,value,cb) {
	//console.log("uid : "+uid+" name : "+name+ " value : "+value)
	var cmd = "nn:acc:"+uid+":"+name
	var oldValue = parseInt(value)
	if(!oldValue){
		cb(false)
		return
	}	
	DBRemote.dbService.db.incrby(cmd,oldValue,function(err,value) {
		if(err){
			console.log(err)
			cb(false)
			return
		}
		if(value < 0){
			//小于0归0
			console.log("error set db value < 0")
			value = 0
			DBRemote.dbService.db.set(cmd,0)
		}
		cb(true)
		if(name === "diamond"){
			//通知钻石更新
			var notify = {
				"cmd" : "updateDiamond",
				"data" : value
			}
			DBRemote.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})		
			//通知后台
			httpConf.sendDiamondHttp(uid,oldValue,value,oldValue > 0 ? "inc" : "dec")				
		}						
	})
}

DBRemote.prototype.changeValue = function(uid,name,value,cb) {
	DBRemote.dbService.setPlayer(uid,name,value,cb)
}

//设置代开房记录
// DBRemote.prototype.setAgencyRoom = function(uid,agencyRoom,cb) {
// 	DBRemote.dbService.getAgencyRoom(uid,function(data) {
// 		for(var i = 9;i > 0;i--){
// 			if(data.List[i - 1]){
// 				data.List[i] = data.List[i - 1]
// 			}
// 		}
// 		data.List[0] = agencyRoom
// 		DBRemote.dbService.setAgencyRoom(uid,data)
// 		if(cb){
// 			cb()
// 		}
// 	})
// }

//更新代开房记录
// DBRemote.prototype.updateAgencyRoom = function(uid,agencyRoom,cb) {
// 	DBRemote.dbService.getAgencyRoom(uid,function(data) {
// 		for(var i = 9;i >= 0;i--){
// 			if(data.List[i]){
// 				//找到并修改代开房记录
// 				if(data.List[i].roomId === agencyRoom.roomId){
// 					data.List[i] = agencyRoom
// 					DBRemote.dbService.setAgencyRoom(uid,data)
// 					if(cb){
// 						cb()
// 					}
// 					return
// 				}
// 			}
// 		}
// 		if(cb){
// 			cb()
// 		}
// 	})
// }
//获取代开房信息记录
// DBRemote.prototype.getAgencyRoom = function(uid,cb) {
// 	DBRemote.dbService.getAgencyRoom(uid,function(data) {
// 		cb(data)
// 	})
// }

DBRemote.prototype.incrbyPlayer = function(uid,name,value,cb) {
	DBRemote.dbService.incrbyPlayer(uid,name,value,cb)
}
DBRemote.prototype.getValue = function(uid,name,cb) {
	DBRemote.dbService.getPlayer(uid,name,cb)
}
DBRemote.prototype.getPlayerObject = function(uid,name,cb) {
	DBRemote.dbService.getPlayerObject(uid,name,cb)
}
DBRemote.prototype.setPlayerObject = function(uid,name,data,cb) {
	DBRemote.dbService.setPlayerObject(uid,name,data,cb)
}
//检查游戏开关
DBRemote.prototype.checkGameSwitch = function(type,cb) {
	DBRemote.dbService.db.get("nn:game:switch",function(err,data) {
		if(!data){
			cb(true)
			return
		}
		var tmpData = JSON.parse(data)
		if(tmpData[type] != undefined  && tmpData[type] == false){
			cb(false)
		}else{
			cb(true)
		}
	})
}

local.getDateString = function() {
	var myDate = new Date()
	var month = myDate.getMonth() + 1
	var date = myDate.getDate()
	if(month < 10){
		month = "0"+month
	}
	if(date < 10){
		date = "0"+date
	}
	var dateString = parseInt(""+myDate.getFullYear() + month + date)
	return dateString
}
//修改密码
DBRemote.prototype.changePassword = function(phone,password,cb) {
	DBRemote.dbService.db.hget("game:phoneAccount",phone,function(err,ps) {
		console.log("ps : ",ps)
		if(err || !ps){
			cb(false,"账号不存在")
			return
		}
		if(password == ps){
			cb(false,"不能和之前的密码一样")
			return
		}
		DBRemote.dbService.db.hset("game:phoneAccount",phone,password,function() {
			cb(true)
			return
		})
	})
}